<template>
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryRef" :inline="true">
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model.trim="queryParams.name"
          placeholder="请输入活动名称"
          @keyup.enter="handleSearch(true)"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model.trim="queryParams.remark"
          placeholder="请输入活动备注"
          @keyup.enter="handleSearch(true)"
        />
      </el-form-item>
      <el-form-item label="选择活动时间" prop="time">
        <el-date-picker
          v-model="queryParams.time"
          type="daterange"
          format="YYYY-MM-DD HH:mm"
          value-format="x"
          date-format="YYYY-MM-DD"
          time-format="HH:mm"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="城市标签" prop="cityName">
        <el-select
          v-model="queryParams.cityName"
          @change="handleSearch(true)"
          fit-input-width
          placeholder="请选择"
        >
          <el-option
            v-for="item in cityNameOptions"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="&nbsp;">
        <el-button @click="handleSearch(false)">重置</el-button>
        <el-button type="primary" @click="handleSearch(true)">查询</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          v-hasPermi="['marketing:punchCard:add']"
          icon="Plus"
          @click="handleAdd()"
          >新增</el-button
        >
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tableList">
      <el-table-column label="活动名称" align="center" prop="name" width="240" />
      <el-table-column label="活动备注" align="center" prop="remark" width="240" />
      <el-table-column label="城市标签" align="center" prop="cityName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="240">
        <template #default="{ row }"> {{ parseTime(row?.createTime) }} </template>
      </el-table-column>
      <el-table-column label="活动时间" align="center" width="340">
        <template #default="{ row }">
          {{ parseTime(row?.startTime) }} - {{ parseTime(row?.endTime) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-button
            :type="row.status === 1 ? 'primary' : row.status === 2 ? 'danger' : 'warning'"
            link
          >
            {{ statusOptions.find((item) => item.value === row.status)?.label }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="打卡奖励" align="center">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViews(row, true)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="参与人数" align="center" prop="userCount">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViews(row, false)">{{
            row?.userCount
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" min-width="200">
        <template #default="{ row }">
          <el-button
            v-hasPermi="['marketing:punchCard:failure']"
            link
            type="primary"
            v-if="row.status === 1 || row.status === 4"
            @click="handleFailure(row)"
            >失效</el-button
          >
          <el-button
            v-hasPermi="['marketing:punchCard:delete']"
            link
            type="primary"
            v-if="row.status === 2 || row.status === 3"
            @click="handleDelete(row)"
            >删除</el-button
          >
          <el-button
            v-hasPermi="['marketing:punchCard:details']"
            link
            type="primary"
            @click="handleDetails(row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList()"
    />

    <dialogDetails ref="dialogRef" @refresh="getList" />
    <rewardList ref="rewardListRef" />
    <participantsList ref="participantsListRef" />
  </div>
</template>
<script setup>
import {
  getPunchCardListApi,
  postAddPunchCardCheckApi,
  deletePunchCardApi,
  deleteFailurePunchCardApi
} from '@/api/marketing/punchCard'
import dialogDetails from './components/details'
import rewardList from './components/rewardList'
import participantsList from './components/participantsList'

import useGlobalStore from '@/store/modules/global'
import { parseTime } from '@/utils/tools'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => globalStore.myCityList)
const router = useRouter()
const showSearch = ref(true)
const loading = ref(false)
const total = ref(0)
const tableList = ref([])
const queryParams = ref({
  name: null,
  status: '',
  time: null,
  pageNum: 1,
  pageSize: 10,
  cityName: cityNameOptions.value[0]
})

const statusOptions = [
  // {
  //   label: '删除',
  //   value: 0
  // },
  {
    label: '进行中',
    value: 1
  },
  {
    label: '已失效',
    value: 2
  },
  {
    label: '已过期',
    value: 3
  },
  {
    label: '待开始',
    value: 4
  }
]
const queryRef = ref()
const dialogRef = ref()
const rewardListRef = ref()
const participantsListRef = ref()
/**搜索/重置 */
function handleSearch(type) {
  if (type) {
    // 搜索
    queryParams.value.pageNum = 1
    getList()
  } else {
    // 重置
    queryRef.value.resetFields()
    handleSearch(true)
  }
}
/**新增 */
function handleAdd() {
  postAddPunchCardCheckApi({ cityName: queryParams.value.cityName })
    .then((res) => {
      console.log(res)
      if (res.data == 1) {
        dialogRef.value.init('', 'add', queryParams.value.cityName)
      } else if (res.data == 0) {
        ElMessage({
          message: '当前已有进行中的活动，无法新建，请先结束后再创建',
          type: 'warning'
        })
      }
    })
    .catch(() => {})
}
/**查看 */
function handleViews(row, type) {
  if (type) {
    rewardListRef.value.init(row, queryParams.value.cityName)
    console.log('查看打卡奖励')
  } else {
    participantsListRef.value.init(row, queryParams.value.cityName)
    console.log('查看参与人数')
  }
}
/**删除 */
function handleDelete(row) {
  ElMessageBox.confirm(`确认要删除${row.name}吗?`, '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  }).then(() => {
    deletePunchCardApi(row.id).then(() => {
      ElMessage({
        message: '删除成功',
        type: 'success'
      })
      getList()
    })
  })
}
/**失效 */
function handleFailure(row) {
  ElMessageBox.confirm(`确认要失效${row.name}吗?`, '系统提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    center: false
  }).then(() => {
    deleteFailurePunchCardApi(row.id).then(() => {
      ElMessage({
        message: '失效成功',
        type: 'success'
      })
      getList()
    })
  })
}
/**详情 */
function handleDetails(row) {
  dialogRef.value.init(row, 'details')
}
/**列表 */
function getList() {
  loading.value = true
  const params = {
    ...queryParams.value,
    startTime: queryParams.value.time?.length ? queryParams.value.time[0] : '',
    endTime: queryParams.value.time?.length ? queryParams.value.time[1] : ''
  }
  delete params.time
  getPunchCardListApi(params)
    .then((res) => {
      loading.value = false
      tableList.value = res?.data?.rows ?? []

      total.value = res?.data?.total ?? 0
    })
    .catch(() => {
      loading.value = false
    })
}
getList()
</script>
<style lang="scss" scoped></style>
